import json
import os
import sys
import random
import traceback
import face_recognition
from PIL import Image, ImageDraw
import joblib
import encoding
import config


def loadImg(fn):
    if not os.path.exists(fn):
        return None
    return face_recognition.load_image_file(fn)


def getEncodings(fn):
    image = loadImg(fn)
    if image is None:
        return None
    face_encodings = face_recognition.face_encodings(image)
    return face_encodings


def detectEncoding(encoding, encodings):
    results = face_recognition.compare_faces(
        encodings, encoding, config.encodingstrict)
    if True in results:
        return True
    return False


def detectFace(img, encodings, strict=config.detectstrict):
    unknown_face_encodings = face_recognition.face_encodings(img)
    for faceencoding in unknown_face_encodings:
        results = face_recognition.compare_faces(
            encodings, faceencoding, strict)

        if True in results:
            return True
    return False


def getCommonFaceEncoding(path):
    encodings = []
    for root, dirs, files in os.walk(path):
        for file in files:
            # 获取文件所属目录
            print(file)
            if file.endswith('.jpeg'):
                currentencodings = getEncodings(os.path.join(root, file))
                for currentencoding in currentencodings:
                    isIn = False
                    for items in encodings:
                        if detectEncoding(currentencoding, items):
                            items.append(currentencoding)
                            isIn = True
                    if isIn == False:
                        encodings.append([currentencoding])

    print(len(encodings))
    if len(encodings) == 0:
        return None
    encodings.sort(key=lambda x: len(x), reverse=True)
    return encodings[0]  # return most encodings array


def dumpFaceEncoding(dir: str, out, strict=config.encodingstrict):
    try:
        print('sstrict is :', strict)
        print('start get encodings from :', dir)
        if dir == '' or dir == None or not os.path.exists(dir):
            print('no valid path')
        jsonFileName = dir.replace('/', '_')+'.'+config.encodingFileType
        if not os.path.exists(out):
            os.mkdir(out)
        outFullPath = os.path.join(out, jsonFileName)
        encoding = getCommonFaceEncoding(dir)
        if os.path.exists(outFullPath):
            os.remove(outFullPath)

        joblib.dump(encoding, outFullPath)

        print('get sucess!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
        return encoding

    except Exception as me:
        print("ERR:")
        print('traceback.print_exc(): ', traceback.print_exc())


def loadFaceEncoding(dir: str):
    if not os.path.exists(dir):
        print('path not exist:', dir)
        return None
    encodings = []
    for root, dirs, files in os.walk(dir):
        for file in files:
            if file.endswith('.'+config.encodingFileType):
                e = joblib.load(os.path.join(root, file))
                for item in e:
                    encodings.append(item)
    return encodings


# dumpFaceEncoding("./images/zw", "./test/zw")

# print(loadFaceEncoding("./test/zw"))
